﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.UI.WebControls;
using EOSCRM.Util ;
using EOSCRM.Domain;
using EOSCRM.Web.Common;
using EOSCRM.Dao;
using EOSCRM.Web.Shared;
using EOSCRM.Web.UserControls;


namespace EOSCRM.Web.Forms.ChucNang
{
    public partial class QLChiPhi : Authentication
    {
        private readonly ChiPhiDao _objDao = new ChiPhiDao();
        private readonly LoDao _loDao = new LoDao();
        private readonly LoaiChiPhiDao _loaicpDao = new LoaiChiPhiDao();
        private readonly KhuVucDao _khuVucDao = new KhuVucDao();
        private string CreateID()
        {
            string ma = "";
            ma = ma + "CP";
            ma = ma + DateTime.Now.Day.ToString("D2") + DateTime.Now.Month.ToString("D2") + DateTime.Now.Year.ToString("D4") + DateTime.Now.Hour.ToString("D2") + DateTime.Now.Minute.ToString("D2") + DateTime.Now.Second.ToString("D2");
            return ma;
        }

        private CHIPHI ItemObj
        {
            get
            {
                if (!ValidateData())
                    return null;

                var kv = new CHIPHI
                {
                    MaChiPhi = txtMaChiPhi.Text.Trim(),
                    Ngay = ConvertUtil.ToDateTime(lbngayhientai.Text.Trim()).Value,
                    LoaiChiPhi = ddlLoaiCP.SelectedValue,
                    ChiPhi1 = int.Parse(txtChiPhi.Text.Trim()),
                    GhiChu = txtnotes.Text.Trim(),
                    MaLo = ddlLo.SelectedValue,
                    MANVNHAP=LoginInfo.MaNV
                    //STARTCODE = txtMaKV.Text.Trim(),
                    //DACBIET = false
                };

                return kv;
            }
        }

        private Mode UpdateMode
        {
            get
            {
                try
                {
                    if (Session[SessionKey.MODE] != null)
                    {
                        var mode = Convert.ToInt32(Session[SessionKey.MODE]);
                        return (mode == Mode.Update.GetHashCode()) ? Mode.Update : Mode.Create;
                    }

                    return Mode.Create;
                }
                catch (Exception)
                {
                    return Mode.Create;
                }
            }
            set
            {
                Session[SessionKey.MODE] = value.GetHashCode();
            }
        }



        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                if (!Page.IsPostBack)
                {
                    ClearForm();
                    lbngayhientai.Text = DateTime.Now.ToString("dd/MM/yyyy"); 
                    LoadKhuVuc();
                    LoadLo(ddlKhuVuc.SelectedValue);
                    LoadLoaiCP();
                    LoadChiPhiLo(ddlLo.SelectedValue, ConvertUtil.ToDateTime(lbngayhientai.Text.Trim()).HasValue ? ConvertUtil.ToDateTime(lbngayhientai.Text.Trim()).Value : DateTime.Now);
                }
            }
            catch (Exception ex)
            {
                DoError(new Message(MessageConstants.E_EXCEPTION, MessageType.Error, ex.Message, ex.StackTrace));
            }
        }
        
        private void BindDataForGrid()
        {
            var objList = _objDao.GetList(ddlLo.SelectedValue, ConvertUtil.ToDateTime(lbngayhientai.Text.Trim()).Value);
            gvList.DataSource = objList;
            gvList.PagerInforText = objList.Count.ToString();
            gvList.DataBind();
        }
        
        public bool ValidateData()
        {
            


            if (ddlLo.SelectedIndex == -1)
            {
                ShowError(String.Format(Resources.Message.E_INVALID_DATA, "Lô"), ddlLo.ClientID);
                return false;
            }

            if (string.Empty.Equals(txtMaChiPhi.Text))
            {
                ShowError(String.Format(Resources.Message.E_INVALID_DATA, "Mã chi phí"), txtMaChiPhi.ClientID);
                return false;
            }

            try
            {
                int.Parse(txtChiPhi.Text.Trim());
            }
            catch (Exception)
            {
                ShowError(String.Format(Resources.Message.E_INVALID_DATA, "Chi phí "), txtChiPhi.ClientID);
                return false;
            }


            return true;
        }

        private void DeleteList()
        {
            try
            {
                // Get list of ids that to be update
                var strIds = Request["listIds"];
                if ((strIds != null) && (!string.Empty.Equals(strIds)))
                {
                    //TODO: check relation before update list

                    var objs = new List<CHIPHI>();
                    var listIds = strIds.Split(',');

                    // Kiem tra relation ship truoc khi delete
                    foreach (var ma in listIds)
                    {
                        if (_objDao.IsInUse(ma))
                        {
                            var msgIsInUse = new Message(MessageConstants.E_OBJECT_IN_USED, MessageType.Info, "chi phí với mã", ma);

                            CloseWaitingDialog();

                            ShowError(ResourceLabel.Get(msgIsInUse));
                            return;
                        }
                    }

                    //Add ma vao danh sách cần delete
                    objs.AddRange(listIds.Select(ma => _objDao.Get(ma)));

                    if (objs.Count > 0)
                    {
                        var msg = _objDao.DeleteList(objs, UserEventLog.ClientHost(), UserEventLog.ClientIP(), LoginInfo.MaNV);
                        if (msg != null)
                        {
                            CloseWaitingDialog();

                            switch (msg.MsgType)
                            {
                                case MessageType.Error:
                                    ShowError(ResourceLabel.Get(msg));
                                    break;

                                case MessageType.Info:
                                    ShowInfor(ResourceLabel.Get(msg));
                                    break;

                                case MessageType.Warning:
                                    ShowWarning(ResourceLabel.Get(msg));
                                    break;
                            }
                        }
                    }
                    else
                    {
                        CloseWaitingDialog();
                    }
                }
            }
            catch (Exception ex)
            {
                DoError(new Message(MessageConstants.E_EXCEPTION, MessageType.Error, ex.Message, ex.StackTrace));
            }
        }

        private void ClearForm()
        {
            txtMaChiPhi.Text = CreateID();
            txtMaChiPhi.ReadOnly = false;
            txtnotes.Text = "";
            txtChiPhi.Text = "0";
            UpdateMode = Mode.Create;

            txtMaChiPhi.Focus();
        }

        private void BindKhuVuc(CHIPHI obj)
        {
            if (obj == null)
                return;
            SetControlValue(txtMaChiPhi.ClientID, obj.MaChiPhi);
            SetReadonly(txtMaChiPhi.ClientID, true);
            SetControlValue(txtChiPhi.ClientID, obj.ChiPhi1.ToString());
            SetControlValue(txtnotes.ClientID, obj.GhiChu);
            SetControlValue(ddlLoaiCP.ClientID, obj.LoaiChiPhi);
            upnlInfor.Update();
        }
        protected void gvList_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            try
            {
                var makv = e.CommandArgument.ToString();

                switch (e.CommandName)
                {
                    case "EditItem":
                        if (!string.Empty.Equals(makv))
                        {
                            var objDb = _objDao.Get(makv);
                            if (objDb != null)
                            {
                                BindKhuVuc(objDb);
                                UpdateMode = Mode.Update;
                            }
                        }

                        CloseWaitingDialog();

                        break;
                }
            }
            catch (Exception ex)
            {
                DoError(new Message(MessageConstants.E_EXCEPTION, MessageType.Error, ex.Message, ex.StackTrace));
            }
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            var info = ItemObj;
            if (info == null)
            {
                CloseWaitingDialog();
                return;
            }

            Message msg;

            // insert new
            if (UpdateMode == Mode.Create)
            {
                if (!HasInsertPermission)
                {
                    CloseWaitingDialog();
                    ShowError(Resources.Message.WARN_PERMISSION_DENIED);
                    return;
                } 

                var tontai = _objDao.Get(txtMaChiPhi.Text.Trim());
                if (tontai != null)
                {
                    CloseWaitingDialog();
                    ShowError("Mã chi phí đã tồn tại", txtMaChiPhi.ClientID);
                    return;
                }
                msg = _objDao.Insert(info, UserEventLog.ClientHost(), UserEventLog.ClientIP(), LoginInfo.MaNV);
            }
            // update
            else
            {
                if (!HasUpdatePermission)
                {
                    CloseWaitingDialog();
                    ShowError(Resources.Message.WARN_PERMISSION_DENIED);
                    return;
                } 
                msg = _objDao.Update(info,UserEventLog.ClientHost(),UserEventLog.ClientIP(),LoginInfo.MaNV);
            }

            CloseWaitingDialog();

            if (msg == null) return;

            if (msg.MsgType != MessageType.Error)
            {
                ShowInfor(ResourceLabel.Get(msg));

                ClearForm();

                // Refresh grid view
                BindDataForGrid();
                
                upnlGrid.Update();
            }
            else
            {
                ShowError(ResourceLabel.Get(msg));
            }
        }

        protected void btnDelete_Click(object sender, EventArgs e)
        {
            try
            {
                // Authenticate
                if (!HasDeletePermission)
                {
                    CloseWaitingDialog();
                    ShowError(Resources.Message.WARN_PERMISSION_DENIED);
                    return;
                }

                DeleteList();
                BindDataForGrid();
                upnlGrid.Update();

                CloseWaitingDialog();
            }
            catch (Exception ex)
            {
                DoError(new Message(MessageConstants.E_EXCEPTION, MessageType.Error, ex.Message, ex.StackTrace));
            }
        }

        protected void btnCancel_Click(object sender, EventArgs e)
        {
            CloseWaitingDialog();
            ClearForm();
        }

        private void LoadLoaiCP()
        {
            var objList = _loaicpDao.GetList();
            CommonFunc.BindDropDownList(ddlLoaiCP, objList, "TenLoaiChiPhi", "MaLoaiChiPhi", false);
        }

        private void LoadKhuVuc()
        {
            var objList = _khuVucDao.GetList();
            CommonFunc.BindDropDownList(ddlKhuVuc, objList, "TenKhuVuc", "MaKhuVuc", false);
        }
        private void LoadLo(string makv)
        {
            var objList = _loDao.GetListKhuVuc(makv);
            CommonFunc.BindDropDownList(ddlLo, objList, "TenLo", "MaLo", false);
        }

        private void LoadChiPhiLo(string malo, DateTime ngay)
        {
            var objList = _objDao.GetList(malo,ngay);
            gvList.DataSource = objList;
            gvList.DataBind();
        }
      

        protected void ddlKhuVuc_SelectedIndexChanged(object sender, EventArgs e)
        {
            ClearForm();
            LoadLo(ddlKhuVuc.SelectedValue);
            LoadChiPhiLo(ddlLo.SelectedValue, ConvertUtil.ToDateTime(lbngayhientai.Text.Trim()).Value);
            upnlGrid.Update();
        }

        protected void ddlLo_SelectedIndexChanged(object sender, EventArgs e)
        {
            ClearForm();
            LoadChiPhiLo(ddlLo.SelectedValue, ConvertUtil.ToDateTime(lbngayhientai.Text.Trim()).Value);
            upnlGrid.Update();
        }
    }
}